from tornado import web 
from tornado import ioloop
from tornado import gen
from tornado.web import Application
from tornado import websocket
import tornado
import motor
import pymongo
import os
import time
import json
import wtforms
from wtforms.fields import StringField, PasswordField
from wtforms.validators import Required
from answer_statistic import Graphy
client = motor.MotorClient()
table = set()


settings = {
	'db' : client,
	'debug' : True,
	'autoreload' : True,
	'login_url':'/login',
}

# class RegisterForm(wtforms.Form):
# 	username = StringField(validators=[Required()])
	# password = PasswordField(validators=[Required()])


class JsonUtils:
	@staticmethod
	def toJson(data):
		return json.dumps(data)

	@staticmethod
	def readJson(info):
		return json.loads(info)

class BaseHandler(web.RequestHandler):

	def prepare(self):
		self.db = self.settings['db']


class RegisterHandler(BaseHandler):

	@gen.engine
	@web.asynchronous
	def check_in_mongo(self,email,name,password,phone):
		user_exist = yield motor.Op(
			self.db.IDS.contact.find_one,{
				'name':email,
				'password' : password,
			}
		)
		if not user_exist :
			new_user = {
				'email':email,
				'name'	:name,
				'password' : password,
				'phone'	: phone,
			}

			self.db.IDS.contact.insert(new_user)
			message = JsonUtils.toJson({
				'response' : 'ok',
			})

			self.write(message)

		else :
			messgae = JsonUtils.toJson({
				'response' : 'This account registed !',		
			})
			self.write(message)

		self.finish()

	@web.asynchronous
	def post(self):
		info = JsonUtils.readJson(self.get_argument('JSON_REGISTER'))
		
		email = info['email']
		password = info['password']
		name = info['name']
		phone = info['phone']
		self.check_in_mongo(email,name,password,phone)

class LoginHandler(BaseHandler):
	table = set()
	@gen.engine
	@web.asynchronous
	def check_in_mongo(self,info,password):
		user_exist = yield motor.Op(
			self.db.IDS.contact.find_one,{
				'name':info,
				'password' : password,
			}
		)
		message = None

		if user_exist :
			message = JsonUtils.toJson({
				'response' : 'ok',
				'email'	: user_exist['email'],
				'name'	: user_exist['name'],
				'phone'	: user_exist['phone']
				})
		else :
			messgae = JsonUtils.toJson({
				'response' : 'Login failed',
				})
		self.log_user(info)
		for one in LoginHandler.table:
			print "user : ",one,"----------------- ON" 
		self.write(message)
		self.finish()
	
	def log_user(self,name):
		
		LoginHandler.table.add(name)
		FILE = open("student.txt","w")
		for user in table :
			FILE.writelines(name+"\n")
		FILE.close()
	@web.asynchronous
	def post(self):

		info = JsonUtils.readJson(self.get_argument('JSON_LOGIN'))
		name = info['info']
		password = info['password'] 

		print ("Login uers : %10s" %name)
		self.check_in_mongo(name,password)

class GraphyHandler(BaseHandler):
	@web.asynchronous
	def post(self):
		info = JsonUtils.readJson(self.get_argument('JSON_GRAPHY'))
		command = info['command']
		graphy = Graphy(command)
		print info 
		print Answer.result
		for key in Answer.result:
			graphy.add_data(key,Answer.result[key])

		self.write(JsonUtils.toJson({
			'response':"start show..."
			}))
		self.finish()
		graphy.show()
		Answer.ini_data()

class Answer(BaseHandler):
	result = {
		'A':0,
		'B':0,
		'C':0,
		'D':0,
	}
	@staticmethod
	def ini_data():
		Answer.result = Answer.result.fromkeys(Answer.result,0)

	@web.asynchronous
	def post(self):
		info=JsonUtils.readJson(self.get_argument('JSON_ANSWER'))
		name = info['name']
		select = info['select']
		Answer.result[select] += 1
		self.check(name,select)

	@web.asynchronous
	def check (self,name,select):
		print "from %s  : %10s " %(name,select)
		message = JsonUtils.toJson({
				'if_T' : name +"You choice %s" %select,
			})
		self.write(message)
		self.finish()


class SendMessageWebSocketHandler(websocket.WebSocketHandler):
	users = {}
	names = set()
	def open(self):
		print ("WebSocket opened")

	def on_message(self,message):
		info =  JsonUtils.readJson(message)
		status = info['status']
		
		if status == "login": 

			name = info['name']
			print "add to room :",name
			self.login(name)
			
		elif status == "talk":
		
			for key in SendMessageWebSocketHandler.users:
				### this for send all message to all users 

				SendMessageWebSocketHandler.users[key].write_message(message)

	def on_close(self):
			
		print ( "Close ...")


	def login(self,user):
		
		#if user not in SendMessageWebSocketHandler.users:
		SendMessageWebSocketHandler.users[user] = self
		
		su = JsonUtils.toJson({
			'status' : 'login',
			'content': 'add to this room',
		})
		print "Now :"
		print SendMessageWebSocketHandler.users
		self.write_message(su)

application = Application([
		(r'/register',RegisterHandler),
		(r'/message',SendMessageWebSocketHandler),
		(r'/answer',Answer),
		(r'/login',LoginHandler),
		(r'/statistic',GraphyHandler),
	],**settings)

if __name__ == "__main__":
	# http_server = tornado.httpserver.HTTPServer(application)
	application.listen(8888)
	ioloop.IOLoop.instance().start()
